const express = require("express");
const os = require("os");
const path = require("path");
const fs = require("fs");
const cors = require("cors"); // 添加 cors 包

// 导入各个模块功能
const { generatePdfFromHtml } = require("./modules/pdfGenerator");
// const { generatePdfFromUrl } = require("./modules/puppeteerPdf");

// 创建 Express 应用
const app = express();
app.use(cors()); // 启用 cors
// 增加请求体大小限制到 50MB
app.use(express.json({ limit: "50mb" }));
app.use(express.urlencoded({ extended: true, limit: "50mb" }));

// 确保 PDF 输出目录存在
const outputDir = path.join(__dirname, "pdfs");
if (!fs.existsSync(outputDir)) {
  fs.mkdirSync(outputDir, { recursive: true });
}

// 获取本地IP地址
function getLocalIP() {
  const interfaces = os.networkInterfaces();
  for (const name of Object.keys(interfaces)) {
    for (const iface of interfaces[name]) {
      if (iface.family === "IPv4" && !iface.internal) {
        return iface.address;
      }
    }
  }
  return "localhost";
}

// 静态文件服务
app.use(express.static(path.join(__dirname, "public")));

// 提供静态HTML页面
app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname, "index.html"));
});

app.get("/order", (req, res) => {
  res.sendFile(path.join(__dirname, "order.html"));
});

// HTML内容生成PDF
app.post("/generatepdf/htmlToPdf", cors(), async (req, res) => {
  const { html, styles, fileName } = req.body;

  if (!html) {
    return res.status(400).json({
      success: false,
      error: "HTML内容不能为空",
    });
  }

  // console.log(styles, "styles");

  try {
    const fullHtml = `
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <style>
          /* 基础样式 */
          body {
            font-size: 14px;
            line-height: 30px;
            -webkit-font-smoothing: antialiased;
          }
          /* 用户自定义样式 */
           ${styles}

        .techniques  table {
            border-collapse: collapse;
            width: 100%;
          }
        .techniques  th, .techniques td {
            border: 0.5pt solid #000 !important;
          }
        </style>
      </head>
      <body>
        ${html}
      </body>
    </html>
  `;

    const resPonseData = await generatePdfFromHtml(
      fullHtml,
      outputDir,
      fileName
    );
    const base64Data = resPonseData.toString("base64");
    res.json({
      success: true,
      message: "PDF生成成功",
      data: base64Data,
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message || "PDF生成失败",
    });
  }
});

// URL生成PDF
// app.post("/api/generatepdf/url", async (req, res) => {
//   const { token, transportPlanCode } = req.body;

//   if (!token) {
//     return res.status(400).json({
//       success: false,
//       error: "缺少必要参数",
//     });
//   }

//   try {
//     const url = `http://localhost:5000/pdfmodel?transportPlanCode=${
//       transportPlanCode || "YSJH20250327000044"
//     }&token=${token}`;
//     await generatePdfFromUrl(url, outputDir);
//     res.json({
//       success: true,
//       message: "PDF生成成功",
//     });
//   } catch (error) {
//     res.status(500).json({
//       success: false,
//       error: error.message || "PDF生成失败",
//     });
//   }
// });

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, "0.0.0.0", () => {
  const localIP = getLocalIP();
  console.log("====================================");
  console.log(`✅  服务已启动`);
  console.log(`🔗  本地访问: http://localhost:${PORT}`);
  console.log(`🌐  网络访问: http://${localIP}:${PORT}`);
  console.log("====================================");
});

// 添加矿业新闻搜索API
app.get("/api/mining-news", async (req, res) => {
  const { keyword } = req.query;

  if (!keyword) {
    return res.status(400).json({
      success: false,
      error: "关键词不能为空",
    });
  }

  try {
    const result = await crawlMiningNews(keyword);
    res.json({
      success: true,
      data: result,
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message || "爬取新闻失败",
    });
  }
});
